package com.sp2p.action.front;

import com.gofull.gateway.sms.util.SMSUtil;
import com.gofull.gateway.wechat.config.WechatConfig;
import com.gofull.gateway.wechat.util.WechatUtils;
import com.shove.Convert;
import com.shove.data.DataException;
import com.shove.security.Encrypt;
import com.shove.util.RandomNo;
import com.shove.util.SqlInfusion;
import com.shove.util.UtilDate;
import com.shove.web.util.DesSecurityUtil;
import com.shove.web.util.JSONUtils;
import com.shove.web.util.ServletUtils;
import com.sp2p.constants.IConstants;
import com.sp2p.entity.User;
import com.sp2p.service.*;
import com.sp2p.service.admin.AdminService;
import com.sp2p.service.admin.FundManagementService;
import com.sp2p.service.admin.RelationService;
import com.sp2p.service.admin.SMSInterfaceService;
import com.sp2p.util.AmountUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class WchatAction extends BaseFrontAction {
	public static Log log = LogFactory.getLog(WchatAction.class);
	private static final long serialVersionUID = 1L;
	private GoFullAwardService goFullAwardService;
	private RechargeService rechargeService;
	private FinanceService financeService;

	public GoFullAwardService getGoFullAwardService() {
		return goFullAwardService;
	}

	public void setGoFullAwardService(GoFullAwardService goFullAwardService) {
		this.goFullAwardService = goFullAwardService;
	}

	private NewsAndMediaReportService newsService;
	protected UserService userService;
	private UserIntegralService userIntegralService;
	private ValidateService validateService;
	private AdminService adminService;
	private RelationService relationService;
	private SMSInterfaceService sMsService;
	protected SendMailService sendMailService;
	private PublicModelService publicModelService;
	private GameService gameService;

	public GameService getGameService() {
		return gameService;
	}

	public void setGameService(GameService gameService) {
		this.gameService = gameService;
	}

	public void setsMsService(SMSInterfaceService sMsService) {
		this.sMsService = sMsService;
	}

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	public void setRelationService(RelationService relationService) {
		this.relationService = relationService;
	}

	public RechargeService getRechargeService() {
		return rechargeService;
	}

	public void setRechargeService(RechargeService rechargeService) {
		this.rechargeService = rechargeService;
	}

	private MyHomeService myHomeService;
	private HomeInfoSettingService homeInfoSettingService;

	public FinanceService getFinanceService() {
		return financeService;
	}

	public void setFinanceService(FinanceService financeService) {
		this.financeService = financeService;
	}

	public HomeInfoSettingService getHomeInfoSettingService() {
		return homeInfoSettingService;
	}

	public void setHomeInfoSettingService(
			HomeInfoSettingService homeInfoSettingService) {
		this.homeInfoSettingService = homeInfoSettingService;
	}

	public MyHomeService getMyHomeService() {
		return myHomeService;
	}

	public void setMyHomeService(MyHomeService myHomeService) {
		this.myHomeService = myHomeService;
	}

	public ValidateService getValidateService() {
		return validateService;
	}

	public void setValidateService(ValidateService validateService) {
		this.validateService = validateService;
	}

	public void setUserIntegralService(UserIntegralService userIntegralService) {
		this.userIntegralService = userIntegralService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public NewsAndMediaReportService getNewsService() {
		return newsService;
	}

	public void setNewsService(NewsAndMediaReportService newsService) {
		this.newsService = newsService;
	}

	private BBSRegisterService bbsRegisterService;

	public void setBbsRegisterService(BBSRegisterService bbsRegisterService) {
		this.bbsRegisterService = bbsRegisterService;
	}

	public void setSendMailService(SendMailService sendMailService) {
		this.sendMailService = sendMailService;
	}

	public void setPublicModelService(PublicModelService publicModelService) {
		this.publicModelService = publicModelService;
	}

	private NewsAndMediaReportService mediaReportService;

	public void setMediaReportService(
			NewsAndMediaReportService mediaReportService) {
		this.mediaReportService = mediaReportService;
	}

	private FundManagementService fundManagementService;

	public FundManagementService getFundManagementService() {
		return fundManagementService;
	}

	public void setFundManagementService(
			FundManagementService fundManagementService) {
		this.fundManagementService = fundManagementService;
	}

	public String index() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();

		// 可用共富券个数
		Map<String, String> availableVoucherCounts = myHomeService
				.queryAvailableVoucherCounts(userId);
		request()
				.setAttribute("availableVoucherCounts", availableVoucherCounts);

		Map<String, String> accmountStatisMap = myHomeService
				.queryAccountStatisInfo(user.getId());
		request().setAttribute("accmountStatisMap", accmountStatisMap);

		// 余额宝
		Map<String, String> yebMap = financeService.queryBorrowProduct(1);
		request().setAttribute("yebMap", yebMap);
		Map<String,String> yebAnnualRate =financeService.queryYebAnnualRate();
		request().setAttribute("yebAnnualRate",yebAnnualRate.get("annualRate"));
		// 月利宝
		Map<String, String> ylbMap = financeService.queryBorrowProduct(2);
		request().setAttribute("ylbMap", ylbMap);
		// 季发宝
		Map<String, String> jfbMap = financeService.queryBorrowProduct(3);
		request().setAttribute("jfbMap", jfbMap);
		// 稳赢宝
		Map<String, String> wybMap = financeService.queryWyb();
		request().setAttribute("wybMap", wybMap);
		// 债权
		Map<String, String> debtMap = financeService.queryDebt();
		request().setAttribute("debtMap", debtMap);

		return "success";
	}

	public String about() throws Exception {
		return "success";
	}

	public String team() throws Exception {
		return "success";
	}

	public String contact() throws Exception {
		return "success";
	}

	public String linksInit() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		String desUserId = "";
		if (userId == null) {
			return "login";
		} else {
			DesSecurityUtil des = new DesSecurityUtil();
			desUserId = des.encrypt(userId + "");
		}

		request().setAttribute("userId", desUserId);
		return "success";
	}

	public String links() throws Exception {
		// 投资用户数
		Map<String, String> userCountMap = userService.queryUserCount();
		String userCount = String.format("%.0f",
				Convert.strToDouble(userCountMap.get("nums"), 0)).toString();
		request().setAttribute("userCount", userCount);

		// 投资总额，总理财收益(总利息+总共富奖励）
		Map<String, String> financeEarnMap = financeService.queryTotalInvest();
		String investAmount = String
				.format(
						"%.0f",
						Convert.strToDouble(financeEarnMap
								.get("totalInvestAmount"), 0) / 10000)
				.toString();
		Map<String, String> gofullAward = goFullAwardService
				.queryTotalGofullAward();
		double income = (Convert.strToDouble(financeEarnMap
				.get("totalRecievedInterest"), 0) + Convert.strToDouble(
				gofullAward.get("totalAwardMoney"), 0)) / 10000;
		String finaceIncome = String.format("%.0f", income).toString();
		request().setAttribute("investAmount", investAmount);
		request().setAttribute("finaceIncome", finaceIncome);

		return "success";
	}

	public String rechargeInit() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		Map<String, String> homeMap = myHomeService.queryHomeInfo(user.getId());
		request().setAttribute("homeMap", homeMap);

		Map<String, String> accmountStatisMap = myHomeService
				.queryAccountStatisInfo(user.getId());
		request().setAttribute("accmountStatisMap", accmountStatisMap);
		return "success";
	}

	public String registerInit() throws Exception {
		String param = SqlInfusion.FilteSqlInfusion(request("param"));
		if (StringUtils.isNotBlank(param)) {
			DesSecurityUtil des = new DesSecurityUtil();
			Long userId = Convert.strToLong(des.decrypt(param), -1);
			String userName;
			Map<String, String> map = new HashMap<String, String>();
			try {
				map = userService.queryUserById(userId);
			} catch (Exception e) {
				log.error(e);
				e.printStackTrace();
			}
			userName = map.get("username");
			// request().setAttribute("refferee", userName);
			paramMap.put("refferee", userName);
			session().setAttribute("reffereeParam", userName);
		}
		paramMap.put("param", param);
		return "success";
	}

	public String bindMobile() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		String mobileNum = request().getParameter("mobileNum");
		request().setAttribute("mobileNum", mobileNum);
		return SUCCESS;
	}

	public void getMoblieVerifyCode() throws Exception {
		String mobile = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
				request("mobileNum"), ""));
		JSONObject obj = new JSONObject();
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			obj.put("code", -1);
			obj.put("msg", "登录状态失效，请重新登录");
			JSONUtils.printObject(obj);
			return;
		}
		if ("".equals(mobile)) {
			obj.put("code", -1);
			obj.put("msg", "手机号码获取异常");
			JSONUtils.printObject(obj);
			return;
		}
		long result1 = userService.queryUserIdByPhone(mobile);
		if (result1 > 0) {
			Map<String, String> userMap = userService
					.queryUserBymobilePhone(mobile);
			if (userMap != null
					&& userMap.get("id").equals(String.valueOf(userId))) {
				obj.put("code", -1);
				obj.put("msg", "账户已验证，请直接登录");
				JSONUtils.printObject(obj);
				return;
			}
			obj.put("code", -1);
			obj.put("msg", "此手机号已与其他账号绑定，请更换手机号");
			JSONUtils.printObject(obj);
			return;
		}
		// 手机号码正常，发送短信
		long sendTimeLast = 0;
		if (null != session().getAttribute("sendTimeLast")) {
			sendTimeLast = (Long) session().getAttribute("sendTimeLast");
		}
		long sendTimeLastNow = System.currentTimeMillis();
		long cost = sendTimeLastNow - sendTimeLast;
		if (sendTimeLast != 0 && cost < 1 * 60 * 1000) {
			obj.put("code", -1);
			obj.put("msg", "短信已发送，请60秒后重试");
			JSONUtils.printObject(obj);
			return;
		}
		StringBuffer telephoneCode = new StringBuffer();
		// 获取验证码
		for (int i = 0; i < 6; i++) {
			telephoneCode.append((int) (Math.random() * 10));
		}
		session().setAttribute("moblieVerifyCode", telephoneCode.toString());
		// 记录当前时间
		long sendTime = System.currentTimeMillis();
		session().setAttribute("sendTimeLast", sendTime);
		Map<String, String> map = sMsService.getSMSById(1);
		SMSUtil
				.sendSMS(map.get("Account"), map.get("Password"), "您的验证码为"
						+ telephoneCode.toString()
						+ "（请在页面输入以完成验证），如非本人操作，请忽略本短信。有问题请致电：4008-893-983",
						mobile, "");
		// 将手机号及认证ID（用户ID）返回,并
		Map<String, Object> dict = new HashMap<String, Object>();
		dict.put("mobile", mobile);
		obj.put("dict", dict);
		JSONUtils.printObject(obj);
	}

	public String bindMobileNext() throws Exception {
		String mobile = SqlInfusion.FilteSqlInfusion(Convert.strToStr(request()
				.getParameter("mobileNum"), "")); // 检验手机号
		User user = this.getUser();
		Long userId = user.getId();
		if ("".equals(mobile) || userId == null) {
			return "login";
		} else {
			request().setAttribute("b_mobile", mobile);
			return SUCCESS;
		}
	}

	public void bindMobileWithVerifyCode() throws Exception {
		JSONObject obj = new JSONObject();
		User user = this.getUser();
		// 获取手机号码
		String telephone = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
				paramMap.get("mobileNum"), null));
		// 获取前台提交手机验证码
		String code = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("verifyCode"), null));
		// 获取前台交易密码
		String payPwd = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("payPwd"), null));
		if (telephone == null || telephone == "") {
			obj.put("code", -1);
			obj.put("msg", "获取手机号码失败");
			JSONUtils.printObject(obj);
			return;
		}
		if (code == null || code == "") {
			obj.put("code", -3);
			obj.put("msg", "获取验证码失败");
			JSONUtils.printObject(obj);
			return;
		}
		if (payPwd == null || payPwd == "") {
			obj.put("code", -2);
			obj.put("msg", "获取交易密码失败");
			JSONUtils.printObject(obj);
			return;
		}
		// 验证手机号码是否已绑定
		Long vidResult = userService.queryUserIdByPhone(telephone);
		if (vidResult > 0) {
			// 该号码已绑定
			obj.put("code", -4);
			obj.put("msg", "该号码已绑定");
			JSONUtils.printObject(obj);
			return;
		}
		// 验证交易密码
		Map<String, String> map = homeInfoSettingService.getDealPwd(user
				.getId());
		// 获得交易密码
		String dealpwd = map.get("dealpwd");// 交易密码默认为登录密码
		if (dealpwd == null || "".equals(dealpwd)) {
			dealpwd = user.getPassword();
		}
		if ("1".equals(IConstants.ENABLED_PASS)) {
			payPwd = com.shove.security.Encrypt.MD5(payPwd);
		} else {
			payPwd = com.shove.security.Encrypt.MD5(payPwd
					+ IConstants.PASS_KEY);
		}
		if (!payPwd.equals(dealpwd)) {// 交易密码输入错误
			obj.put("code", -2);
			obj.put("msg", " 交易密码输入错误");
			JSONUtils.printObject(obj);
			return;
		}
		String telephoneCode = new String();
		telephoneCode = (String) session().getAttribute("moblieVerifyCode");
		if (telephoneCode == null || telephoneCode == "") {
			obj.put("code", -8);
			obj.put("msg", " 系统异常");
			JSONUtils.printObject(obj);
			return;
		}
		if (code.equals(telephoneCode)) {
			Long result = userService.updataUserCellphone(user.getId(),
					telephone);
			if (result > 0) {
				// 移除验证码
				session().setAttribute("moblieVerifyCode", "");
				user.setIsBindMobile(1);
				session().setAttribute("user", user);
				// 绑定手机成功
				obj.put("code", 1);
				JSONUtils.printObject(obj);
			}
			return;
		} else {
			obj.put("code", -3);
			obj.put("msg", " 验证码错误");
			JSONUtils.printObject(obj);
			return;
		}
	}

	public String bindMobileSuccess() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		return SUCCESS;
	}

	public String wchatRealNameAuthen() throws Exception {
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user != null) {
			Map<String, String> pmap = userService
					.queryPersonById(user.getId());
			// paramMap = userService.queryUserById(user.getId());
			if (user.getIsBindIdNo() == 1) {
				String idNo = pmap.get("idNo");
				String IdCardNo = idNo.substring(0, 3) + "***"
						+ idNo.substring(6, 10) + "********";
				request().setAttribute("IdCardNo", IdCardNo);
				// 已认证则跳到认证成功页面
				return SUCCESS;
			}
			// 跳到认证页面
			return SUCCESS;
		} else {
			// 跳到登录页面
			return "login";
		}
	}

	public String wchatRealNameAuthen3() throws Exception {
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user != null) {
			// 跳到认证成功页面
			return SUCCESS;
		} else {
			// 跳到登录页面
			return "login";
		}
	}

	public String wchatPersonInit() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		Map<String, String> personMap = userService.queryPersonById(userId);
		request().setAttribute("personMap", personMap);

		return "success";
	}

	public String fundsFlow() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		Map<String, String> accmountStatisMap = myHomeService
				.queryAccountStatisInfo(user.getId());
		request().setAttribute("map", accmountStatisMap);

		List<Map<String, Object>> fundMap = myHomeService.queryFundRecord(user
				.getId());
		request().setAttribute("fundMap", fundMap);

		return "success";
	}

	public String bankManager() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		try {
			List<Map<String, Object>> lists = homeInfoSettingService
					.queryBankInfoList(userId);
			request().setAttribute("lists", lists);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}

		return "success";
	}

	public String bankCardBinding() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		// 身份认证
		Map<String, String> materialsauth = validateService.querymaterialsauth(
				user.getId(), 1);
		String auditStatus = materialsauth.get("auditStatus");
		if (auditStatus == null || !auditStatus.equals("3")) {
			return "person";
		}

		Map<String, String> personMap = userService.queryPersonById(userId);
		request().setAttribute("personMap", personMap);

		return "success";
	}

	public String withdrawInit() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		Map<String, String> newstatusmap = userService.querynewStatus(userId);

		Map<String, String> withdrawNumMap = rechargeService
				.querywithdrawNum(userId);// 提现次数
		request()
				.setAttribute("withdrawNum", withdrawNumMap.get("withdrawNum"));

		Map<String, String> freeNumMap = rechargeService.queryNum();// 提现免费次数
		request().setAttribute("freeNum", freeNumMap.get("freeNum"));

		Map<String, String> FeeRateMap = rechargeService.queryFeeRate();// 提现费率
		request().setAttribute("FeeRate", FeeRateMap.get("FeeRate"));
		try {
			List<Map<String, Object>> lists = rechargeService
					.withdrawLoad(userId);
			// 需要加载信息 真实姓名 手机号码 帐户余额 可用余额 冻结总额 提现银行
			String realName = user.getRealName();
			String bindingPhone = "";
			int status = -1;
			String[] vals = moneyVal(userId);

			request().setAttribute("handleSum", vals[0]);
			request().setAttribute("usableSum", vals[1]);
			request().setAttribute("freezeSum", vals[2]);
			request().setAttribute("max_withdraw", IConstants.WITHDRAW_MAX);// 最大提现金额，超过之后要收取手续费
			if (lists != null && lists.size() > 0) {
				if (lists.get(0).get("cellPhone") != null) {
					bindingPhone = lists.get(0).get("cellPhone") + "";
				}
				if (lists.get(0).get("status") != null) {
					status = Convert.strToInt(lists.get(0).get("status")
							.toString(), -1);
				}
				// 绑定的银行卡信息单独查询
				List<Map<String, Object>> banks = homeInfoSettingService
						.querySuccessBankInfoList(userId);
				request().setAttribute("banks", banks);
				request()
						.setAttribute("realName", newstatusmap.get("realName"));
				request().setAttribute("bindingPhone", bindingPhone);
			}
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}

		return "success";
	}

	public String[] moneyVal(long userId) throws Exception {
		String[] val = new String[3];
		for (int i = 0; i < val.length; i++) {
			val[i] = "0";
		}
		try {
			Map<String, String> map = userService.queryUserById(userId);
			if (map != null) {
				double usableSum = Convert.strToDouble(map.get("usableSum"), 0);
				double freezeSum = Convert.strToDouble(map.get("freezeSum"), 0);
				double handleSum = usableSum + freezeSum;
				val[0] = String.format("%.2f", handleSum);// df.format(handleSum);
				val[1] = String.format("%.2f", usableSum);// df.format(usableSum);
				val[2] = String.format("%.2f", freezeSum);// df.format(freezeSum);
			}
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
		return val;
	}

	public String myAccount() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		Map<String, String> accmountStatisMap = myHomeService
				.queryAccountStatisInfo(user.getId());
		request().setAttribute("accmountStatisMap", accmountStatisMap);

		// 可用共富券个数
		Map<String, String> availableVoucherCounts = myHomeService
				.queryAvailableVoucherCounts(userId);
		request().setAttribute("availableVoucherCounts", availableVoucherCounts);

		return "success";
	}



	public String investSum() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		// 各数量总额统计
		Map<String, String> accmountStatisMap = myHomeService
				.queryAccountStatisInfo(user.getId());
		request().setAttribute("map", accmountStatisMap);
		return "success";
	}

	public String investRecyle() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));

		String title = "";
		String publisher = "";
		String publishTimeStart = "";
		String publishTimeEnd = "";

		paramMap.put("title", title);
		paramMap.put("publisher", publisher);
		paramMap.put("publishTimeStart", publishTimeStart);
		paramMap.put("publishTimeEnd", publishTimeEnd);

		myHomeService.queryInvestCurrentRecord(title, publishTimeStart,
				publishTimeEnd, user.getId(), pageBean, publisher);

		List<Map<String, Object>> pageList = pageBean.getPage();
		if (pageList != null && pageList.size() > 0) {
			for (int i = 0; i < pageList.size(); i++) {
				Map<String, Object> map = pageList.get(i);
				double realAmount = Convert.strToDouble(map.get("realAmount")
						.toString(), 0);
				double annualRate = Convert.strToDouble(map.get("annualRate")
						.toString(), 2);
				double recievedInterest = Convert.strToDouble(map.get(
						"recievedInterest").toString(), 0);
				double notPI = Convert.strToDouble(map.get("notPI").toString(),
						0);
				map.put("realAmount", String.format("%.2f", realAmount));
				map.put("annualRate", String.format("%.2f", annualRate));

				map.put("notPI", String.format("%.2f", notPI));
				if (map.get("isDayThe").toString().equals("1")) {
					int deadline = Convert.strToInt(map.get("deadline")
							.toString(), 0);
					recievedInterest = recievedInterest / deadline;
				}
				map.put("recievedInterest", String.format("%.2f",
						recievedInterest));
				// 借款期限
				String repayDate = "";
				if (null != map.get("repayDate")) {
					repayDate = map.get("repayDate").toString();
					String deadline = map.get("deadline").toString();
					if (map.get("isDayThe").toString().equals("1")) { // 不是天标
						map.put("deadLine", map.get("deadline") + "个月");
						String theMonth = repayDate.substring(5, 7);
						String theYear = repayDate.substring(0, 4);
						int month = Integer.parseInt(theMonth);
						if (!map.get("paymentMode").toString().equals("4")) {
							month = Integer.parseInt(theMonth)
									+ Integer.parseInt(deadline) - 1;
						}
						if (month / 12 > 0) {
							theYear = Integer.parseInt(theYear) + month / 12
									+ "";
							theMonth = month - 12 * (month / 12) + "";
						} else {
							theMonth = month + "";
						}
						if (theMonth.length() == 1) {
							theMonth = "0" + theMonth;
						}
						repayDate = theYear + "-" + theMonth
								+ repayDate.substring(7, 10);
					} else {
						map.put("deadLine", map.get("deadline") + "天");
					}
				}
				map.put("finalRepayDate", repayDate);
			}
		}

		return "success";
	}

	public String investRecyled() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));

		String title = "";
		String publisher = "";
		String publishTimeStart = "";
		String publishTimeEnd = "";

		paramMap.put("title", title);
		paramMap.put("publisher", publisher);
		paramMap.put("publishTimeStart", publishTimeStart);
		paramMap.put("publishTimeEnd", publishTimeEnd);

		myHomeService.queryInvestSuccessedRecord(title, publishTimeStart,
				publishTimeEnd, user.getId(), pageBean, publisher);

		List<Map<String, Object>> pageList = pageBean.getPage();
		if (pageList != null && pageList.size() > 0) {
			for (int i = 0; i < pageList.size(); i++) {
				Map<String, Object> map = pageList.get(i);
				double realAmount = Convert.strToDouble(map.get("realAmount")
						.toString(), 0);
				double totalIncome = Convert.strToDouble(map.get("notPI")
						.toString(), 0)
						+ Convert.strToDouble(map.get("hasPI").toString(), 0)
						- Convert.strToDouble(map.get("realAmount").toString(),
								0);
				double hasPI = Convert.strToDouble(map.get("hasPI").toString(),
						0);
				map.put("realAmount", String.format("%.2f", realAmount));
				map.put("hasPI", String.format("%.2f", hasPI));
				map.put("totalIncome", String.format("%.2f", totalIncome));
			}
		}
		return "success";
	}

	public String aboutDynamicList() throws Exception {
		// 公告
		List<Map<String, Object>> newsList = new ArrayList<Map<String, Object>>();
		pageBean.setPageSize(5);
		newsService.frontQueryNewsPage(pageBean);
		if (null != pageBean.getPage()) {
			List<Map<String, Object>> lists = pageBean.getPage();

			String titlemin = "";
			for (Map<String, Object> map : lists) {
				if (null != map.get("title")
						&& map.get("title").toString().length() > 20) {
					titlemin = map.get("title").toString().substring(0, 20)
							+ "...";
				} else {
					titlemin = map.get("title") + "";
				}
				map.put("titlemin", titlemin);
			}
		}

		newsList = pageBean.getPage();
		pageBean.setPage(null);
		request().setAttribute("newsList", newsList);
		return "success";
	}

	public String logout() throws Exception {
		// 清除微信免登录状态
		User user = (User) session().getAttribute("user");
		if (null != user) {
			userService.unbindWchatAutoLoginInfo(user.getId());
		}

		session().removeAttribute("user");
		session().invalidate();
		return SUCCESS;
	}

	public String repaySituation() throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");

		int month = Convert.strToInt(request("month"),
				new Date().getMonth() + 1);
		int year = Convert.strToInt(request("year"), Integer.valueOf(sdf
				.format(new Date())));

		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		List<HashMap<String, Object>> daysAcount = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> dayAcount = myHomeService.queryDayAcount(
				year, month, user.getId().toString());
		// 对daysAcount做处理，方便前台打印显示

		// 得到这个月的第一天星期几
		Date now = new Date();
		now.setMonth(month - 1);
		now.setDate(1);
		int day = now.getDay();
		for (int i = 0; i < day; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("day", "");
			map.put("amount", "");
			daysAcount.add((HashMap<String, Object>) map);
		}

		daysAcount.addAll(dayAcount);

		if ((daysAcount.size() % 7) != 0) {
			int length = 7 - (daysAcount.size() % 7);
			for (int i = 0; i < length; i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("day", "");
				map.put("amount", "");
				daysAcount.add((HashMap<String, Object>) map);
			}
		}
		// {realRepayDate=2013, hasPIYearAcount=997.33}
		// {realRepayDate=2013, hasPIMonthAcount=338.90}
		Map<String, String> monthAcount = myHomeService.queryMonthAcounta(year,
				month, user.getId().toString());
		Map<String, String> yearAcount = myHomeService.queryYearAcounta(year,
				user.getId().toString());

		request().setAttribute("daysAcount", daysAcount);
		request().setAttribute("monthAcount", monthAcount);
		request().setAttribute("yearAcount", yearAcount);
		request().setAttribute("month", month);
		request().setAttribute("year", year);

		return "success";
	}

	public String borrowDetail() throws Exception {
		// 最新借款列表
		List<Map<String, Object>> mapList = financeService.queryLastestBorrow();
		// 只显示固定长度标题
		String borrowTitle = "";
		String time = "";
		String publistime = "";
		if (mapList != null) {
			for (Map<String, Object> map : mapList) {
				if (map.get("borrowTitle").toString().length() > 10) {
					borrowTitle = map.get("borrowTitle").toString().substring(
							0, 10);
					map.put("borrowTitle", borrowTitle + "...");
				}
				if (map.get("fullBorrowTime") != null
						&& map.get("fullBorrowTime") != "") {
					time = map.get("fullBorrowTime").toString()
							.substring(5, 16);
					map.put("fullBorrowTime", time);
				}
				if (map.get("publishTime") != null
						&& map.get("publishTime") != "") {
					publistime = map.get("publishTime").toString().substring(2,
							16).replace("-", "").replace(" ", "").replace(":",
							"");

					// map.put("publishTime", Convert.strToInt(publistime, -1));
					map.put("publishTime", publistime);
				}
			}
		}
		request().setAttribute("mapList", mapList);

		return "success";
	}

	public String financeDetail() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		} else {
			Map<String, String> accmountStatisMap = myHomeService
					.queryAccountStatisInfo(user.getId());
			request().setAttribute("accmountStatisMap", accmountStatisMap);
		}

		String idStr = SqlInfusion
				.FilteSqlInfusion(request().getParameter("id") == null ? ""
						: request().getParameter("id"));
		if (!"".equals(idStr) && StringUtils.isNumericSpace(idStr)) {
			Long id = Convert.strToLong(idStr, -1);

			// 借款详细
			Map<String, String> borrowDetailMap = financeService
					.queryBorrowDetailById(id);

			if (borrowDetailMap != null && borrowDetailMap.size() > 0) {
				double borrowSum = Convert.strToDouble(borrowDetailMap
						.get("borrowSum")
						+ "", 0);
				double annualRate = Convert.strToDouble(borrowDetailMap
						.get("annualRate")
						+ "", 0);
				int deadline = Convert.strToInt(borrowDetailMap.get("deadline")
						+ "", 0);
				int hasDeadline = Convert.strToInt(borrowDetailMap
						.get("hasDeadline")
						+ "", 0);
				int paymentMode = Convert.strToInt(borrowDetailMap
						.get("paymentMode")
						+ "", -1);
				int isDayThe = Convert.strToInt(borrowDetailMap.get("isDayThe")
						+ "", 1);

				double hkjd = (Double.parseDouble(String.valueOf(hasDeadline)) / Double
						.parseDouble(String.valueOf(deadline))) * 100;
				borrowDetailMap.put("hkjd", String.format("%.2f", hkjd));

				double investAmount = borrowSum;
				String earnAmount = "";
				if (borrowSum < investAmount) {
					investAmount = borrowSum;
				}
				AmountUtil au = new AmountUtil();
				Map<String, String> earnMap = null;

				request().setAttribute("borrowDetailMap", borrowDetailMap);

				// 借款人资料
				Map<String, String> borrowUserMap = financeService
						.queryUserInfoById(id);
				request().setAttribute("borrowUserMap", borrowUserMap);

			} else {
				return "404";
			}
		} else {
			return "404";
		}
		return "success";
	}

	// 设定密保问题
	public String setSecurityQuestion() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		// 根据用户ID查询安全问题
		Map<String, String> map = userService.queryQuestion(userId);
		if (null != map && map.size() > 1) {
			return "change";
		} else {
			return "success";
		}
	}

	public String setSecurityQuestion2() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		// 根据用户ID查询安全问题
		Map<String, String> map = userService.queryQuestion(userId);
		if (null != map && map.size() > 1) {
			request().setAttribute("errorTip", "密保问题已经设立");
			return "error";
		} else {
			String question = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
					paramMap.get("securityQuestion"), null));
			String answer = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
					paramMap.get("answer"), null));
			if (null == question || null == answer) {
				request().setAttribute("errorTip", "系统异常，密保问题设立失败");
				return "error";
			}
			long result = -1;
			long result1 = -1;
			result = userService.addQuestion(user.getId(), question, answer);
			result1 = userService.updateUserSafeFlag(user.getId());
			if (result > 0 && result1 > 0) {
				// 成功则修改session中的值
				session().setAttribute("isBindQuestion", 1);
				return SUCCESS;
			} else {
				request().setAttribute("errorTip", "系统异常，密保问题设立失败");
				return "error";
			}
		}
	}

	// 修改密保问题
	public String changeSecretQuestion() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		// 根据用户ID查询安全问题
		Map<String, String> map = userService.queryQuestion(userId);
		if (null != map && map.size() > 1) {
			return "success";
		} else {
			return "set";
		}
	}

	public String changeSecretQuestion2() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		String question = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
				paramMap.get("newsecretQuestion"), null));
		String answer = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("newanswer"), null));
		String oldQuestion = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
				paramMap.get("securityQuestion"), null));
		String oldAnswer = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
				paramMap.get("answer"), null));
		// 根据用户ID查询安全问题
		Map<String, String> map = userService.queryOldAnswer(user.getId(),
				oldAnswer, oldQuestion);
		if (null != map && map.size() > 1) {
			long result = -1;
			result = userService.updateQuestion(user.getId(), question, answer);
			if (result > 0) {
				return SUCCESS;
			} else {
				request().setAttribute("errorTip", "系统异常，密保问题设立失败");
				return "error";
			}
		} else {
			request().setAttribute("errorTip", "原问题或密码不正确");
			return "error";
		}
	}

	public String modifyLoginPwd() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		return SUCCESS;
	}

	public void updateLoginPsdWithNoForward() throws Exception {
		JSONObject obj = new JSONObject();
		String captcha = Convert.strToStr(paramMap.get("captcha"), null);
		String newPass = Convert.strToStr(paramMap.get("newPassword"), null);
		String confirmPass = Convert.strToStr(paramMap.get("confirmPassword"),
				null);
		// add by lw 判断交易面的长度 6 - 16
		if (newPass.length() < 6 || newPass.length() > 16) {
			obj.put("code", -4);
			obj.put("msg", "密码长度为6-16位");
			JSONUtils.printObject(obj);
			return;
		}
		// end
		if (!newPass.equals(confirmPass)) {
			obj.put("code", -1);
			obj.put("msg", "两次新密码不一致");
			JSONUtils.printObject(obj);
			return;
		}

		// 获取用户的信息
		User user = (User) session().getAttribute(IConstants.SESSION_USER);

		try {

			String newPassDecode = "";
			String autoPwd = session().getAttribute("autoPwdCode") == null ? ""
					: session().getAttribute("autoPwdCode").toString();
			String isAutoPwd = Encrypt.MD5(user.getMobilePhone() + captcha); 
			if ("1".equals(IConstants.ENABLED_PASS)) {
				newPassDecode = com.shove.security.Encrypt.MD5(newPass);
			} else {
				newPassDecode = com.shove.security.Encrypt.MD5(newPass
						+ IConstants.PASS_KEY);
			}
			
			if (!isAutoPwd.equals(autoPwd)) {// 动态码输入错误
				obj.put("code", -2);
				obj.put("msg", "动态码输入错误");
				JSONUtils.printObject(obj);
				session().removeAttribute("sendTimeLast");
				session().removeAttribute("autoPwdCode");
				return;
			}
			session().removeAttribute("sendTimeLast");
			session().removeAttribute("autoPwdCode");
			
			if (newPassDecode.equals(user.getPassword())) {// 新密码与旧密码相同
				obj.put("code", -5);
				obj.put("msg", "新密码与旧密码相同");
				JSONUtils.printObject(obj);
				return;
			}
			long result = homeInfoSettingService.updateUserPassword(user.getId(),
					newPass, "login");

			if (result < 0) {
				obj.put("code", -3);
				obj.put("msg", "登录密码更新失败,请稍后再试");
				JSONUtils.printObject(obj);
				return;
			} else {
				// 更新session中user登录密码
				user.setPassword(newPassDecode);
				session().setAttribute(IConstants.SESSION_USER, user);
				obj.put("code", 1);
				JSONUtils.printObject(obj);
				return;
			}
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}

	}

	public String modifyPayPwd() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		return SUCCESS;
	}

	public void updatePayPsdWithNoForward() throws Exception {
		JSONObject obj = new JSONObject();
		String captcha = Convert.strToStr(paramMap.get("captcha"), null);
		String newPass = Convert.strToStr(paramMap.get("newPassword"), null);
		String confirmPass = Convert.strToStr(paramMap.get("confirmPassword"),
				null);
		
		// add by lw 判断交易面的长度 6 - 16
		if (newPass.length() < 6 || newPass.length() > 16) {
			obj.put("code", -4);
			obj.put("msg", "密码长度为6-16位");
			JSONUtils.printObject(obj);
			return;
		}
		// end
		if (!newPass.equals(confirmPass)) {
			obj.put("code", -1);
			obj.put("msg", "两次新密码不一致");
			JSONUtils.printObject(obj);
			return;
		}

		// 获取用户的信息
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		String autoPwd = session().getAttribute("autoPwdCode") == null ? ""
				: session().getAttribute("autoPwdCode").toString();
		String isAutoPwd = Encrypt.MD5(user.getMobilePhone() + captcha); 
		try {
			String newPassDecode = "";
			if ("1".equals(IConstants.ENABLED_PASS)) {
				newPassDecode = com.shove.security.Encrypt.MD5(newPass);
			} else {
				newPassDecode = com.shove.security.Encrypt.MD5(newPass
						+ IConstants.PASS_KEY);
			}
			
			if (!isAutoPwd.equals(autoPwd)) {// 动态码输入错误
				obj.put("code", -2);
				obj.put("msg", "动态码输入错误");
				JSONUtils.printObject(obj);
				session().removeAttribute("sendTimeLast");
				session().removeAttribute("autoPwdCode");
				return;
			}
			session().removeAttribute("sendTimeLast");
			session().removeAttribute("autoPwdCode");
			
			/*if (newPassDecode.equals(user.getPassword())) {// 新的交易密码与登录密码相同
				obj.put("code", -5);
				obj.put("msg", "新密码与旧密码相同");
				JSONUtils.printObject(obj);
				return;
			}*/
			long result = homeInfoSettingService.updateUserPassword(user.getId(),
					newPass, "deal");

			if (result < 0) {
				obj.put("code", -3);
				obj.put("msg", "支付密码更新失败,请稍后再试");
				JSONUtils.printObject(obj);
				return;
			} else {
				obj.put("code", 1);
				JSONUtils.printObject(obj);
				return;
			}
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
	}

	public String modifyLoginPwdSuccess() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		return SUCCESS;
	}

	public String getAccountBalanceInfo() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		Map<String, String> accmountStatisMap = myHomeService
				.queryAccountStatisInfo(user.getId());
		request().setAttribute("accmountStatisMap", accmountStatisMap);
		return SUCCESS;
	}

	// 余额宝
	public String getYebInvestorRecord() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		pageBean.setPageNum(SqlInfusion
				.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		myHomeService.queryInvestYebRecordDetail(user.getId(), pageBean);
		if (pageBean.getTotalNum() > 0) {
			request().setAttribute("yebInvestorRecordList", pageBean.getPage());
		} else {
			request().setAttribute("yebInvestorRecordList", null);

		}
		request().setAttribute("currentPage", pageBean.getPageNum());
		request().setAttribute("totalPageNum", pageBean.getTotalPageNum());
		return SUCCESS;
	}

	// 月利宝投资记录
	public String getYlbInvestorRecord() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		pageBean.setPageNum(SqlInfusion
				.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		myHomeService.queryInvestProductRecord(2, -1, user.getId(), pageBean);
		if (pageBean.getTotalNum() > 0) {
			request().setAttribute("ylbInvestorRecordList", pageBean.getPage());
		} else {
			request().setAttribute("ylbInvestorRecordList", null);

		}
		request().setAttribute("currentPage", pageBean.getPageNum());
		request().setAttribute("totalPageNum", pageBean.getTotalPageNum());
		return SUCCESS;
	}

	// 稳赢宝投资记录
	public String getJfbInvestorRecord() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		pageBean.setPageNum(SqlInfusion
				.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		myHomeService.queryInvestProductRecord(3, -1, user.getId(), pageBean);
		if (pageBean.getTotalNum() > 0) {
			request().setAttribute("jfbInvestorRecordList", pageBean.getPage());
		} else {
			request().setAttribute("jfbInvestorRecordList", null);

		}
		request().setAttribute("currentPage", pageBean.getPageNum());
		request().setAttribute("totalPageNum", pageBean.getTotalPageNum());
		return SUCCESS;
	}

	// 稳赢宝投资记录
	public String getWybInvestorRecord() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		pageBean.setPageNum(SqlInfusion
				.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		myHomeService.queryInvestProductRecord(4, -1, user.getId(), pageBean);
		if (pageBean.getTotalNum() > 0) {
			request().setAttribute("wybInvestorRecordList", pageBean.getPage());
		} else {
			request().setAttribute("wybInvestorRecordList", null);

		}
		request().setAttribute("currentPage", pageBean.getPageNum());
		request().setAttribute("totalPageNum", pageBean.getTotalPageNum());
		return SUCCESS;
	}
	
	/**
	 * @Return:
	 * @Descb: 20天加薪宝
	 * @Throws:
	 */
	public String jxbIndex() throws Exception {
		// 微信公众号接口
		Map<String, String> wxConfigMap = WechatUtils.jSdkConfig(request());
		request().setAttribute("wxConfigMap", wxConfigMap);
		
		List<Map<String, Object>> jxbList = financeService.queryJxbLastestBorrow();
		request().setAttribute("jxbList", jxbList);
		
		return "success";
	}

	// 我的共富券记录
	public String wchatVoucher() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}
		
		pageBean.setPageNum(SqlInfusion
				.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		myHomeService.queryAllVoucherList(user.getId(), pageBean);
		
		// 可用共富券个数
		Map<String, String> availableVoucherCounts = myHomeService
				.queryAvailableVoucherCounts(userId);
		request()
				.setAttribute("availableVoucherCounts", availableVoucherCounts);
		
		if (pageBean.getTotalNum() > 0) {
			request().setAttribute("voucherRecordList", pageBean.getPage());
		} else {
			request().setAttribute("voucherRecordList", null);

		}
		request().setAttribute("currentPage", pageBean.getPageNum());
		request().setAttribute("totalPageNum", pageBean.getTotalPageNum());
		return SUCCESS;
	}

	// 手机找回密码
	public String inputMobile4ResetPwd() throws Exception {
		String mobile = SqlInfusion.FilteSqlInfusion(request("mobile"));
		request().setAttribute("mobile", mobile);
		return SUCCESS;
	}

	// 获取手机验证码
	public void getMobileCode4ResetPwd() throws Exception {
		JSONObject obj = new JSONObject();
		Map<String, String> userMap = (Map<String, String>) session()
				.getAttribute("findPwdMap");
		int type = Convert.strToInt(paramMap.get("type"), -1); // 是否再次发送短信验证
		String mobile = SqlInfusion.FilteSqlInfusion(paramMap.get("mobile")
				.toString().trim()); // 手机号
		if (type > 0) {
			if (null == userMap || userMap.size() <= 0) {
				obj.put("code", -99);
				obj.put("msg", "操作超时，请重试");
				JSONUtils.printObject(obj);
				return;
			}
		} else {
			String pageId = SqlInfusion
					.FilteSqlInfusion(paramMap.get("pageId")); // 验证码
			String code = (String) session()
					.getAttribute(pageId + "_checkCode");
			String _code = SqlInfusion.FilteSqlInfusion(paramMap.get("captcha")
					.toString().trim());
			if (code == null || !_code.equals(code)) {
				obj.put("code", -1);
				obj.put("msg", "验证码输入错误，请检查");
				JSONUtils.printObject(obj);
				return;
			}
			// TODO 校验用户名是否存在
			userMap = userService.queryUserByUserName(mobile);
			if (null == userMap || userMap.size() <= 0) {
				obj.put("code", -1);
				obj.put("msg", "没有与此手机号对应的账户");
				JSONUtils.printObject(obj);
				return;
			}
			String uid = userMap.get("id");
			StringBuffer authenTem = new StringBuffer();
			for (int i = 0; i < 2; i++) {
				authenTem.append((int) (Math.random() * 10));
			}
			userMap.put("mobileAuthenId", uid + authenTem.toString());

		}
		// 手机号码正常，发送短信
		long sendTimeLast = 0;
		if (null != session().getAttribute("sendTimeLast")) {
			sendTimeLast = (Long) session().getAttribute("sendTimeLast");
		}
		long sendTimeLastNow = System.currentTimeMillis();
		long cost = sendTimeLastNow - sendTimeLast;
		if (type > 0 && sendTimeLast != 0 && cost < 1 * 60 * 1000) {
			obj.put("code", -1);
			obj.put("msg", "短信已发送，请60秒后重试");
			JSONUtils.printObject(obj);
			return;
		}
		StringBuffer telephoneCode = new StringBuffer();
		// 获取验证码
		for (int i = 0; i < 6; i++) {
			telephoneCode.append((int) (Math.random() * 10));
		}
		session().setAttribute("mobileCode4Reset", telephoneCode.toString());
		// 记录当前时间
		long sendTime = System.currentTimeMillis();
		session().setAttribute("sendTimeLast", sendTime);
		Map<String, String> map = sMsService.getSMSById(1);
		SMSUtil.sendSMS(map.get("Account"), map.get("Password"),
				"【共富网】尊敬的共富网用户，您好！您在共富网重置密码的手机验证码为" + telephoneCode.toString()
						+ "（请在页面输入以完成验证），如非本人操作，请忽略本短信。有问题请致电：4008-893-983",
				mobile, "");

		session().setAttribute("findPwdMap", userMap);
		// 将手机号及认证ID（用户ID+随机2位数）返回,
		obj.put("code", 1);
		Map<String, Object> dict = new HashMap<String, Object>();
		dict.put("mobile", mobile);
		dict.put("mobileAuthenId", userMap.get("mobileAuthenId"));
		obj.put("dict", dict);
		JSONUtils.printObject(obj);
	}

	public String preVerifyMobile4ResetPwd() throws Exception {
		String mobile = SqlInfusion.FilteSqlInfusion(request("mobile"));
		String mai = SqlInfusion.FilteSqlInfusion(request("mai"));
		request().setAttribute("mobile", mobile);
		request().setAttribute("mai", mai);
		return SUCCESS;
	}

	public void verifyMobileCode4ResetPwd() throws Exception {
		JSONObject obj = new JSONObject();
		Map<String, String> userMap = (Map<String, String>) session()
				.getAttribute("findPwdMap");
		if (null == userMap || userMap.size() <= 0) {
			obj.put("code", -99);
			obj.put("msg", "操作超时，请重试");
			JSONUtils.printObject(obj);
		}
		// 获取手机号码
		String telephone = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
				paramMap.get("mobile"), null));
		// 获取前台提交手机验证码
		String code = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("code"), null));
		// 获取前台交易密码
		String mai = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("mai"), null));
		if (telephone == null || telephone == "") {
			obj.put("code", -1);
			obj.put("msg", "获取手机号码失败");
			JSONUtils.printObject(obj);
			return;
		}
		if (code == null || code == "") {
			obj.put("code", -3);
			obj.put("msg", "获取验证码失败");
			JSONUtils.printObject(obj);
			return;
		}
		if (mai == null || mai == "") {
			obj.put("code", -2);
			obj.put("msg", "获取认证ID失败");
			JSONUtils.printObject(obj);
			return;
		}
		// 校验用户认证ID
		String mobileAuthenId = userMap.get("mobileAuthenId");
		if (!mai.equals(mobileAuthenId)) {
			obj.put("code", -2);
			obj.put("msg", "用户认证ID失败，请重试");
			JSONUtils.printObject(obj);
			return;
		}
		String telephoneCode = new String();
		telephoneCode = (String) session().getAttribute("mobileCode4Reset");
		if (telephoneCode == null || telephoneCode == "") {
			obj.put("code", -8);
			obj.put("msg", " 系统异常，请重试");
			JSONUtils.printObject(obj);
			return;
		}
		if (code.equals(telephoneCode)) {
			obj.put("code", 1);
			JSONUtils.printObject(obj);
			return;
		} else {
			obj.put("code", -3);
			obj.put("msg", " 验证码错误");
			JSONUtils.printObject(obj);
			return;
		}
	}

	public String verifySuccess4ResetPwd() throws Exception {
		Map<String, String> userMap = (Map<String, String>) session()
				.getAttribute("findPwdMap");
		if (null == userMap || userMap.size() <= 0) {
			return "init";
		}
		return SUCCESS;
	}

	public void resetPwd() throws Exception {
		JSONObject obj = new JSONObject();
		String newPass = Convert.strToStr(paramMap.get("pwd"), null);
		String confirmPass = Convert.strToStr(paramMap.get("rePassword"), null);
		Map<String, String> userMap = (Map<String, String>) session()
				.getAttribute("findPwdMap");
		if (null == userMap || userMap.size() <= 0) {
			obj.put("code", -99);
			obj.put("msg", "操作失败，请重试");
			JSONUtils.printObject(obj);
			return;
		}
		if (newPass.length() < 6 || newPass.length() > 20) {// 密码长度
			obj.put("code", -2);
			obj.put("msg", "密码长度，请重试");
			JSONUtils.printObject(obj);
			return;
		}
		// end
		if (!newPass.equals(confirmPass)) {// 两次输入密码不一致
			obj.put("code", -3);
			obj.put("msg", "两次输入密码不一致");
			JSONUtils.printObject(obj);
			return;
		}
		try {
			Long id = Convert.strToLong(userMap.get("id"), -1);// 获得用户编号

			long result = homeInfoSettingService.updateUserPassword(id,
					newPass, "login");

			if (result < 0) {// 修改失败
				obj.put("code", -1);
				obj.put("msg", "操作失败，请重试");
				JSONUtils.printObject(obj);
			} else {// 修改成功
				obj.put("code", 1);
				JSONUtils.printObject(obj);
			}
		} catch (DataException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (SQLException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
			throw e;
		}
	}

	public String resetPwdSuccessByMobile() throws Exception {
		return SUCCESS;
	}

	// 邮箱找回密码
	public String inputMail4ResetPwd() throws Exception {
		return SUCCESS;
	}

	// 发送重置密码链接
	public void sendMail4ResetPwd() throws Exception {
		JSONObject obj = new JSONObject();
		String email = SqlInfusion.FilteSqlInfusion(paramMap.get("mail")
				.toString().trim()); // 手机号
		String pageId = SqlInfusion.FilteSqlInfusion(paramMap.get("pageId")); // 验证码
		String code = (String) session().getAttribute(pageId + "_checkCode");
		String _code = SqlInfusion.FilteSqlInfusion(paramMap.get("captcha")
				.toString().trim());
		if (code == null || !_code.equals(code)) {
			obj.put("code", -1);
			obj.put("msg", "验证码输入错误，请检查");
			JSONUtils.printObject(obj);
			return;
		}
		// TODO 校验用户名是否存在
		Map<String, String> userMap = userService.queryUserByUserName(email);
		if (null == userMap || userMap.size() <= 0) {
			obj.put("code", -1);
			obj.put("msg", "没有与此邮箱对应的账户");
			JSONUtils.printObject(obj);
			return;
		}
		// 邮箱正常发送邮件
		// ===截取emal后面地址
		int dd = email.indexOf("@");
		String mailAddress = null;
		if (dd >= 0) {
			mailAddress = "mail." + email.substring(dd + 1);
		}
		String username = null;
		Long userId = null;
		if (userMap != null && userMap.size() > 0) {
			username = userMap.get("username");
			userId = Convert.strToLong(userMap.get("id"), -1L);
			DesSecurityUtil des = new DesSecurityUtil();
			String key1 = des.encrypt(userId.toString());
			String key2 = des.encrypt(new Date().getTime() + "");
			String url = getPath(); // request().getRequestURI();
			String VerificationUrl = url + "changePassword.do?username="
					+ username + "&key=" + key1 + "$" + key2;
			sendMailService.sendRetakePasswordVerificationEmail(
					VerificationUrl, username, email);
			// session().setAttribute("VerificationUrl", VerificationUrl);
			obj.put("code", 1);
			JSONUtils.printObject(obj);
		} else {
			obj.put("code", -99);
			obj.put("msg", "发送邮件失败，请重试");
			JSONUtils.printObject(obj);
		}
	}

	public String resetPwdSuccessByMail() throws Exception {
		return SUCCESS;
	}

	public String wchatHelp() throws Exception {
		String d = Convert.strToStr(request().getParameter("d"), "");
		String f = Convert.strToStr(request().getParameter("f"), "");
		// 余额宝常见问题等
		if ("yeb".equals(d) && "yebIntro".equals(f)) {
			return "yebIntro";
		}
		if ("yeb".equals(d) && "yebFaq".equals(f)) {
			return "yebFaq";
		}
		if ("yeb".equals(d) && "yebProfitCal".equals(f)) {
			return "yebProfitCal";
		}
		// 月利宝常见问题等
		if ("ylb".equals(d) && "ylbIntro".equals(f)) {
			return "ylbIntro";
		}
		if ("ylb".equals(d) && "ylbFaq".equals(f)) {
			return "ylbFaq";
		}
		if ("ylb".equals(d) && "ylbProfitCal".equals(f)) {
			return "ylbProfitCal";
		}
		// 季发宝常见问题等
		if ("jfb".equals(d) && "jfbIntro".equals(f)) {
			return "jfbIntro";
		}
		if ("jfb".equals(d) && "jfbFaq".equals(f)) {
			return "jfbFaq";
		}
		if ("jfb".equals(d) && "jfbProfitCal".equals(f)) {
			return "jfbProfitCal";
		}
		// 稳赢宝常见问题等
		if ("wyb".equals(d) && "wybIntro".equals(f)) {
			return "wybIntro";
		}
		if ("wyb".equals(d) && "wybFaq".equals(f)) {
			return "wybFaq";
		}
		if ("wyb".equals(d) && "wybProfitCal".equals(f)) {
			return "wybProfitCal";
		}

		// 新手专享问题等
		if ("novice".equals(d) && "noviceGuide".equals(f)) {
			return "noviceGuide";
		}
		if ("novice".equals(d) && "novicePrivilege".equals(f)) {
			return "novicePrivilege";
		}
		/*
		 * try{ List<Map<String, Object>> listMap =
		 * callCenterService.queryHelpQuestions();
		 * request().setAttribute("listMap", listMap); }catch(Exception e){
		 * log.error(e); e.printStackTrace(); throw e; }
		 */

		return SUCCESS;
	}

	public String wchatMediaIndex() throws Exception {
		pageBean.setPageNum(request().getParameter("PAGE_NO_KEY"));
		pageBean.setPageSize(10);
		mediaReportService.queryMediaReportPage(pageBean);
		List<Map<String, Object>> lists = pageBean.getPage();
		String remark = "";
		String formartTime = "";
		if (lists != null) {
			for (Map<String, Object> map : lists) {
				/*
				 * if (map.get("remark").toString().length() > 50) { remark =
				 * map.get("remark").toString().substring(0, 50);
				 * map.put("remark", remark + "..."); }
				 */
				if (null != map.get("publishTime")) {
					formartTime = map.get("publishTime").toString().substring(
							0, 10).replace("-", ".");
					map.put("publishTime", formartTime);
				}
			}
		}
		request().setAttribute("reportList", lists);
		return SUCCESS;
	}

	public String frontQueryWchatMediaReportById() throws Exception {
		Long id = Convert.strToLong(request("id"), -1);
		try {
			Map<String, String> map = mediaReportService.getMediaReportById(id);
			if (null != map && map.size() > 0) {
				if (!StringUtils.isEmpty(map.get("publishTime"))) {
					String formatTime = map.get("publishTime").substring(0, 10)
							.replace("-", ".");
					map.put("publishTime", formatTime);
				}
			}
			request().setAttribute("map", map);
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return SUCCESS;
	}

	// 玩游戏领取红包
	public String getRedEnvelopesInit() throws Exception {
		String mobile = SqlInfusion.FilteSqlInfusion(request("mobile"));
		String senvKey = SqlInfusion.FilteSqlInfusion(request("senvKey"));
		session().setAttribute("mobile_redEnvelopes", mobile);
		session().setAttribute("senvKey_redEnvelopes", senvKey);
		request().setAttribute("username", getRandomString(4) + mobile);
		return "register";
	}

	public String wchatRegisterByRedEnvelopesFir() throws Exception {
		JSONObject obj = new JSONObject();
		String pageId = SqlInfusion.FilteSqlInfusion(paramMap.get("pageId")); // 验证码
		String userName = SqlInfusion
				.FilteSqlInfusion(paramMap.get("userName")); // 用户名
		if (userName.length() < 2 || userName.length() > 20) {
			obj.put("error", "1");// 用户名长度为2-20个字符
			JSONUtils.printObject(obj);
			return null;
		}
		if (StringUtils.isBlank(userName)) {
			obj.put("error", "2");// 用户名不能为空
			JSONUtils.printObject(obj);
			return null;
		}
		// 验证用户名木含有特殊字符串处理第一个字符不可以是下划线开始 ^[^@\/\'\\\"#$%&\^\*]+$
		if (userName.replaceAll("^[\u4E00-\u9FA5A-Za-z0-9_]+$", "").length() != 0) {
			obj.put("error", "3");// 用户名不能含有特殊字符
			JSONUtils.printObject(obj);
			return null;
		}
		// 判断第一个字符串不能使以下划线开头的
		String fristChar = userName.substring(0, 1);
		if (fristChar.equals("_")) {
			obj.put("error", "4");// 用户名不能以下划线开头
			JSONUtils.printObject(obj);
			return null;
		}
		if (StringUtils.isNotBlank(userName)) {
			long results = userService.isExistEmailORUserName(null, userName);
			if (results > 0) {
				obj.put("error", "0");// 用户名存在
				JSONUtils.printObject(obj);
				return null;
			} else {
				// ---add by houli 首先检查用户表中是否有重复的名字，如果没有则去t_admin表中
				Map<String, String> map = adminService.queryIdByUser(userName);
				if (map != null && map.size() > 0) {
					obj.put("error", "0");// 用户名存在
					JSONUtils.printObject(obj);
					return null;
				}
			}
		}
		String password = SqlInfusion
				.FilteSqlInfusion(paramMap.get("password")); // 用户密码
		String md5Password = password;
		if (StringUtils.isBlank(password)) {
			obj.put("error", "5");// 密码不能为空
			JSONUtils.printObject(obj);
			return null;
		}
		String confirmPassword = SqlInfusion.FilteSqlInfusion(paramMap
				.get("confirmPassword")); // 用户确认密码
		if (StringUtils.isBlank(confirmPassword)) {
			obj.put("error", "6");// 确认密码不能为空
			JSONUtils.printObject(obj);
			return null;
		}
		// 判断密码是否一致
		if (!password.equals(confirmPassword)) {
			obj.put("error", "7");// 两次输入的密码不一致
			JSONUtils.printObject(obj);
			return null;
		}
		// add by hejiangfeng 增加在注册的时候录入验证码
		String code = (String) session().getAttribute(pageId + "_checkCode");
		String _code = SqlInfusion.FilteSqlInfusion(paramMap.get("code")
				.toString().trim());
		if (code == null || !_code.equals(code)) {
			obj.put("_checkCode", "1"); // 验证码错误
			JSONUtils.printObject(obj);
			return null;
		}
		// 第一步只是验证用户和密码，直接保存用户接下来再验证邮箱或者手机
		if ("1".equals(IConstants.ENABLED_PASS)) {
			md5Password = com.shove.security.Encrypt.MD5(md5Password.trim());
		} else {
			md5Password = com.shove.security.Encrypt.MD5(md5Password.trim()
					+ IConstants.PASS_KEY);
		}

		Long userId = -1L;
		userId = userService.userRegister1("", userName, md5Password, null,
				null, -1, null, 0);
		if (userId < 0) {
			obj.put("error", "12");
			JSONUtils.printObject(obj);
			return null;
		} else {
			// 将成功注册的用户id和用户名存放在session中用于后面的激活操作
			User regUser = new User();
			regUser.setUserName(userName);
			regUser.setPassword(md5Password);
			session().removeAttribute("regUser");
			session().setAttribute("regUser", regUser);
			session().removeAttribute("regUserId");
			session().setAttribute("regUserId", userId);
			session().removeAttribute("regUserName");
			session().setAttribute("regUserName", userName);
			// obj.put("regUserId", userId);//若注册成功则将用户ID传回到前台页面
			// JSONUtils.printObject(obj);

		}
		return null;
	}

	public String wchatRegisterByRedEnvelopesSec() throws Exception {
		// 获取用户领取红包的手机号
		String mobile = (String) session().getAttribute("mobile_redEnvelopes");

		// 获取手机号码失败则取消
		if (null == mobile || "".equals(mobile)) {
			return "reg";
		}

		request().setAttribute("mobileLast", mobile);
		return SUCCESS;
	}

	public void verifyMobileCode4RegisterByRedEnvelopes() throws Exception {
		String confirmTelephone = SqlInfusion
				.FilteSqlInfusion((String) session().getAttribute(
						"telephoneCodeReg"));
		String _confirmTelephone = SqlInfusion.FilteSqlInfusion(Convert
				.strToStr(paramMap.get("code"), ""));
		String mobile = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("mobile"), ""));
		Long mai = Convert.strToLong(paramMap.get("mai"), -1);
		Long userId = (Long) session().getAttribute("regUserId");
		JSONObject obj = new JSONObject();
		if (confirmTelephone == null
				|| !_confirmTelephone.equals(confirmTelephone)) {
			obj.put("code", -1);
			obj.put("msg", "验证码输入错误，请检查");
			JSONUtils.printObject(obj);
		} else if (!mai.equals(userId)) {
			obj.put("code", -1);
			obj.put("msg", "验证失败，请重新验证");
			JSONUtils.printObject(obj);
		} else {
			// 手机号码验证成功
			if (userId != null && userId > 0) {
				// 判断是否已经验证
				Map<String, String> userMap = userService
						.queryUserBymobilePhone(mobile);
				if (userMap != null
						&& userMap.get("id").equals(String.valueOf(userId))) {
					obj.put("code", -1);
					obj.put("msg", "账户已验证，请直接登录");
					JSONUtils.printObject(obj);
					return;
				}
				// 移除验证码
				session().setAttribute("telephoneCodeReg", "");
				// 将手机号更新到新注册的用户表中
				long result = -1;
				result = userService.updateMobilePhone(userId, mobile);
				result = userService.updateCellPhone(userId, mobile);
				if (result > 0) {
					// 发放红包
					String senvKey = (String) session().getAttribute(
							"senvKey_redEnvelopes");
					DesSecurityUtil des = new DesSecurityUtil();
					String[] deParam = des.decrypt(senvKey).split("\\|");
					Long senvId = Convert.strToLong(deParam[0], -1L);
					gameService.spliteEnvelopeToEliteNewuser(senvId, userId,
							mobile);

					// 直接登录
					User user = (User) session().getAttribute("user"); // 获取登录的用户session
					User regUser = (User) session().getAttribute("regUser"); // 获取刚刚注册的用户session
					DateFormat dateformat = new SimpleDateFormat(
							UtilDate.simple);
					String lastIP = ServletUtils.getRemortIp();
					String lastTime = dateformat.format(new Date());
					user = userService.userLogin2(regUser.getUserName(),
							regUser.getPassword(), lastIP, lastTime);
					session().setAttribute("user", user);

					obj.put("code", 1);
					JSONUtils.printObject(obj);
				} else {
					obj.put("code", -1);
					obj.put("msg", "验证失败，请重新验证");
					JSONUtils.printObject(obj);
				}
			}
		}
	}

	public String myElite() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		Map<String, String> availableEliteMap = myHomeService
				.queryAvailableElite(user.getId()); // 体验金余额
		Map<String, String> tEliteInterestMap = myHomeService
				.queryTdEliteInterest(user.getId());// 今日收益
		Map<String, String> expectInterestMap = myHomeService
				.queryExpectEliteInterest(user.getId());// 待领取收益

		List<Map<String, String>> eliteRecords = myHomeService
				.queryEliteRecord(user.getId()); // 获取记录
		List<Map<String, String>> eliteInvestRecords = myHomeService
				.queryEliteInvestRecord(user.getId()); // 投资记录

		request().setAttribute("availableEliteMap", availableEliteMap);
		request().setAttribute("tEliteInterestMap", tEliteInterestMap);
		request().setAttribute("expectInterestMap", expectInterestMap);
		request().setAttribute("eliteRecordsSize", eliteRecords.size());
		request().setAttribute("eliteInvestRecordsSize",
				eliteInvestRecords.size());
		return SUCCESS;
	}

	public String eliteInvestIndex() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		Map<String, String> availableEliteMap = myHomeService
				.queryAvailableElite(user.getId()); // 体验金余额
		Map<String, String> lastEliteProduct = myHomeService
				.queryLastEliteProduct();// 体验金理财项目

		request().setAttribute("availableEliteMap", availableEliteMap);
		request().setAttribute("lastEliteProduct", lastEliteProduct);
		return SUCCESS;
	}

	public String eliteInvest() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		// 判断可用体验余额是否大于0
		Map<String, String> aElite = myHomeService.queryAvailableElite(user
				.getId());
		double availableElite = Convert.strToDouble(aElite.get("amount"), -1d);
		if (availableElite <= 50) {
			return "failed";
		}

		// 体验金投资
		Map<String, String> result = myHomeService.addEliteInvest(user.getId());
		String resultMSG = result.get("ret_desc");
		if (!"".equals(resultMSG)) {
			return "failed";
		}

		Map<String, String> lastEliteProduct = myHomeService
				.queryLastEliteProduct();// 体验金理财项目

		// 计算投资到期日
		int deadline = Convert.strToInt(lastEliteProduct.get("deadline"), 0);
		int isDayThe = Convert.strToInt(lastEliteProduct.get("isDayThe"), 0);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		if (isDayThe == 1) {
			c.add(Calendar.MONTH, deadline);
		} else if (isDayThe == 2) {
			c.add(Calendar.DAY_OF_MONTH, deadline);
		}
		request().setAttribute("settleDate", sf.format(c.getTime()));

		return SUCCESS;
	}

	public String getEliteRecords() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		List<Map<String, String>> eliteRecords = myHomeService
				.queryEliteRecord(user.getId()); // 获取记录

		request().setAttribute("eliteRecords", eliteRecords);
		return SUCCESS;
	}

	public String getEliteInvestorRecords() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return "login";
		}

		List<Map<String, String>> eliteInvestRecords = myHomeService
				.queryEliteInvestRecord(user.getId()); // 投资记录

		request().setAttribute("eliteInvestRecords", eliteInvestRecords);
		return SUCCESS;
	}

	public String eliteReceiveAll() throws Exception {
		User user = (User) session().getAttribute("user");

		// 判断待领取收益是否大于0
		Map<String, String> eInterest = myHomeService
				.queryExpectEliteInterest(user.getId());
		double expectInterest = Convert.strToDouble(eInterest
				.get("expectInterest"), -1d);
		if (expectInterest <= 0) {
			return "failed";
		}

		// 领取所有收益
		Map<String, String> result = myHomeService
				.eliteReceiveAll(user.getId());
		String resultMSG = result.get("ret_desc");
		if (!"".equals(resultMSG)) {
			return "failed";
		}

		return SUCCESS;
	}

	private String getRandomString(int length) { // length表示生成字符串的长度
		String base = "abcdefghijklmnopqrstuvwxyz";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public String wchatAutoLogin() throws Exception {
		 String code = request("code");
		 if (null == code || "".equals(code)) {
		 return "failed";
		 }
		
		 Map<String, String> map = WechatUtils.getOauth2AccessToken(
		 WechatConfig.APPID, WechatConfig.APPSECRET, code);
		 int errcode = Convert.strToInt(map.get("errcode"), 0);
		 String unionid = Convert.strToStr(map.get("unionid"), "");
		 if (errcode > 0 || "".equals(unionid)) {
		 return "failed";
		 }

		 // 微信服务号用户信息入库
		 userService.updateWechatUserInfo(map.get("openid"));
		 session().setAttribute("unionid", unionid);
		 
		 User user = (User) session().getAttribute("user");
		 if (null != user) {
			 return "index";
		 }
		
		 Map<String, String> autoInfo = userService
		 .queryWchatAutoLoginInfo(unionid);
		 if (null != autoInfo && autoInfo.size() > 0) {
		 int isAuto = Convert.strToInt(autoInfo.get("isAuto"), 0);
		 long uid = Convert.strToLong(autoInfo.get("userId"), -1);
		 if (isAuto == 1 && uid > 0) {
		 user = userService.wchatAutoLoginSession(uid);
		 session().setAttribute("user", user);
		 return "index";
		 }
		 }

		return "login";
	}

	public String loginInit() throws Exception {
		String mobile = SqlInfusion.FilteSqlInfusion(Convert.strToStr(
				request("mobile"), ""));
		request().setAttribute("mobile", mobile);
		Map<String, String> userMap = userService
				.queryUserBymobilePhone(mobile);
		if (null != userMap) {
			return "stockUser";
		}
		return "newUser";
	}

	public void getAutoPwd() throws Exception {
		JSONObject obj = new JSONObject();
		String mobile = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("mobile"), ""));
		String pageId = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("pageId"), ""));
		String authCode = (String) session().getAttribute(pageId + "_checkCode");
		String _code = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("authCode"), ""));
		if ("".equals(mobile)) {
			obj.put("code", "failed");
			obj.put("msg", "动态密码获取异常");
			JSONUtils.printObject(obj);
			return;
		}

		if (authCode == null || !_code.equals(authCode)) {
			obj.put("code", "failed");
			obj.put("msg", "图形验证码错误，请重新输入");
			JSONUtils.printObject(obj);
			return;
		}

		// 手机号码正常，发送短信
		long sendTimeLast = 0;
		if (null != session().getAttribute("sendTimeLast")) {
			sendTimeLast = (Long) session().getAttribute("sendTimeLast");
		}
		long sendTimeLastNow = System.currentTimeMillis();
		long cost = sendTimeLastNow - sendTimeLast;
		if (sendTimeLast != 0 && cost < 1 * 60 * 1000) {
			obj.put("code", "failed");
			obj.put("msg", "短信已发送，请60秒后重试");
			JSONUtils.printObject(obj);
			return;
		}
		// 获取验证码
		String autoPwd = RandomNo.getRandom(100000, 999999) + "";
		String autoPwdCode = Encrypt.MD5(mobile + autoPwd);//加密处理验证码
		session().setAttribute("autoPwdCode", autoPwdCode);
		// 记录当前时间
		long sendTime = System.currentTimeMillis();
		session().setAttribute("sendTimeLast", sendTime);
		Map<String, String> map = sMsService.getSMSById(1);
		SMSUtil.sendSMS(map.get("Account"), map.get("Password"), "您的动态码为"
				+ autoPwd + "（请在页面输入以完成验证），如非本人操作，请忽略本短信。有问题请致电：4008-893-983",
				mobile, "");

		obj.put("code", "success");
		JSONUtils.printObject(obj);
	}

	public void wchatLogin() throws Exception {
		JSONObject obj = new JSONObject();
		DateFormat dateformat = new SimpleDateFormat(UtilDate.simple);

		String pageId = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("pageId"), ""));
		String authCode = (String) session().getAttribute(pageId + "_checkCode");
		String _code = SqlInfusion.FilteSqlInfusion(Convert.strToStr(paramMap
				.get("authCode"), ""));

		if (authCode == null || !_code.equals(authCode)) {
			obj.put("code", "loginFailed");
			obj.put("msg", "图形验证码错误，请重新输入");
			JSONUtils.printObject(obj);
			return;
		}

		String mobile = SqlInfusion.FilteSqlInfusion(paramMap.get("mobile"));
		String password = SqlInfusion.FilteSqlInfusion(paramMap.get("password"));
		User user = (User) session().getAttribute("user");
		String autoPwd = session().getAttribute("autoPwdCode") == null ? ""
				: session().getAttribute("autoPwdCode").toString();
		String isAutoPwd = Encrypt.MD5(mobile + password); //动态密码是MD5加密处理过的
		if (isAutoPwd.equals(autoPwd)) { //验证码登录
			Map<String, String> userMap = userService
					.queryUserBymobilePhone(mobile);
			long uid = Convert.strToLong(userMap.get("id"), -1);
			user = userService.wchatAutoLoginSession(uid);
		} else {	//密码登录
			try {
				user = userService.userLogin1(mobile, password, null,
						ServletUtils.getRemortIp(), dateformat
								.format(new Date()));
			} catch (Exception e) {
				e.printStackTrace();
				throw e;
			}
		}

		if (null == user) {
			obj.put("code", "loginFailed"); // 用户名或密码错误！
			obj.put("msg", "密码错误！");
			JSONUtils.printObject(obj);
			return;
		}
		
		// 查找数据库对象中的enable属性
		if (user.getEnable() == 2) {
			obj.put("code", "userForbidden"); // 该用户已被锁定
			obj.put("msg", "该用户已被锁定！");
			JSONUtils.printObject(obj);
			return;
		}
		session().setAttribute("user", user);
		session().removeAttribute("sendTimeLast");
		session().removeAttribute("autoPwdCode");
		
		// 微信绑定免登录
		String unionid = session().getAttribute("unionid") == null ? ""
				: session().getAttribute("unionid").toString();
		if (!"".equals(unionid)) {
			Map<String, String> autoInfo = userService
					.queryWchatAutoLoginInfo(user.getId());
			if (null != autoInfo && autoInfo.size() > 0) {
				userService.updateWchatAutoLoginInfo(user.getId(), unionid, 1);
			} else {
				userService.addWchatAutoLoginInfo(user.getId(), unionid, 1);
			}
		}
		obj.put("code", "success");
		JSONUtils.printObject(obj);
	}

	public void wchatRegister() throws Exception {
		JSONObject obj = new JSONObject();
		DateFormat dateformat = new SimpleDateFormat(UtilDate.simple);

		String mobile = SqlInfusion.FilteSqlInfusion(paramMap.get("mobile"));
		String captcha = SqlInfusion.FilteSqlInfusion(paramMap.get("captcha"));
		String userName = getRandomString(4) + mobile; // 用户名
		String password = IConstants.PASS_KEY;
		String md5Password = "";
		if ("1".equals(IConstants.ENABLED_PASS)) {
			md5Password = com.shove.security.Encrypt.MD5(password.trim());
		} else {
			md5Password = com.shove.security.Encrypt.MD5(password.trim()
					+ IConstants.PASS_KEY);
		}

		String autoPwd = session().getAttribute("autoPwdCode") == null ? ""
				: session().getAttribute("autoPwdCode").toString();
		String isAutoPwd = Encrypt.MD5(mobile + captcha); 
		if (!isAutoPwd.equals(autoPwd)) {
			obj.put("code", "registerFailed"); // 动态码错误
			obj.put("msg", "动态码错误！");
			JSONUtils.printObject(obj);
			return;
		}

		Long userId = userService.userRegister1("", userName, md5Password, "",
				null, -1, mobile, 0);
		if (userId > 0) {
			User user = userService.userLogin1(mobile, password, null,
					ServletUtils.getRemortIp(), dateformat.format(new Date()));
			session().setAttribute("user", user);
			// 微信绑定免登录
			String unionid = session().getAttribute("unionid") == null ? ""
					: session().getAttribute("unionid").toString();
			if (!"".equals(unionid)) {
				Map<String, String> autoInfo = userService
						.queryWchatAutoLoginInfo(user.getId());
				if (null != autoInfo && autoInfo.size() > 0) {
					userService.updateWchatAutoLoginInfo(user.getId(), unionid, 1);
				} else {
					userService.addWchatAutoLoginInfo(user.getId(), unionid, 1);
				}
			}
		} else {
			obj.put("code", "registerFailed"); // 动态码错误
			obj.put("msg", "动态码错误！");
			JSONUtils.printObject(obj);
			return;
		}
		session().removeAttribute("sendTimeLast");
		session().removeAttribute("autoPwdCode");
		obj.put("code", "success");
		JSONUtils.printObject(obj);
	}
	
	public String wchatAutoInvestInit() throws Exception {
		// 自动投标设置
		User user = (User) session().getAttribute("user");
		Map<String, String> automaticBidMap = myHomeService.queryAutomaticBid(user.getId());
		request().setAttribute("automaticBidMap", automaticBidMap);
		return SUCCESS;
	}
	
	public void wchatAutomaticBidClose() throws Exception {
		JSONObject obj = new JSONObject();
		User user = (User) session().getAttribute("user");
		long bidStatusLong = 2;
		long returnId = myHomeService.automaticBidSet(bidStatusLong, user.getId());

		if (returnId <= 0) {
			obj.put("msg", "未保存自动投标设置");
		} else {
			obj.put("msg", "操作成功");
		}
		JSONUtils.printObject(obj);
	}
	
	public void wchatAutomaticBidModify() throws Exception {
		JSONObject obj = new JSONObject();
		User user = (User) session().getAttribute("user");
		long returnId = -1;
		String bidAmount = paramMap.get("bidAmount") == null ? "" : paramMap
				.get("bidAmount");
		String rateStart =SqlInfusion.FilteSqlInfusion( paramMap.get("rateStart") == null ? "" : paramMap
				.get("rateStart"));
		String rateEnd ="18";
		String deadlineStart ="-1";
		String deadlineEnd = SqlInfusion.FilteSqlInfusion(paramMap.get("deadlineEnd") == null ? ""
				: paramMap.get("deadlineEnd"));
		String creditStart = SqlInfusion.FilteSqlInfusion(paramMap.get("creditStart") == null ? ""
				: paramMap.get("creditStart"));
		String creditEnd = SqlInfusion.FilteSqlInfusion(paramMap.get("creditEnd") == null ? "" : paramMap
				.get("creditEnd"));
		String remandAmount = SqlInfusion.FilteSqlInfusion(paramMap.get("remandAmount") == null ? ""
				: paramMap.get("remandAmount"));
		Double bidAmountDouble = Convert.strToDouble(bidAmount, 0);
		Double rateStartDouble = Convert.strToDouble(rateStart, 0);
		Double rateEndDouble = Convert.strToDouble(rateEnd, 0);
		Double deadlineStartDouble = Convert.strToDouble(deadlineStart, 0);
		Double deadlineEndDouble = Convert.strToDouble(deadlineEnd, 0);
		Double creditStartDouble = Convert.strToDouble(creditStart, 0);
		Double creditEndDouble = Convert.strToDouble(creditEnd, 0);
		Double remandAmountDouble = Convert.strToDouble(remandAmount, 0);
		boolean bool=true;
		try{
			double b = Double.parseDouble(remandAmount);
		}catch(Exception e){
			bool=false;
		}
		if (StringUtils.isBlank(rateStart)) {
			obj.put("msg", "利率范围开始不可为空");
			JSONUtils.printObject(obj);
			return;
		} else if (rateStartDouble == 0) {
			obj.put("msg", "利率范围开始格式错误");
			JSONUtils.printObject(obj);
			return;
		} else if (rateStartDouble < 1 || rateStartDouble > 24) {
			obj.put("msg", "年利率范围1%-24%，请在此范围内选择利率");
			JSONUtils.printObject(obj);
			return;
		}
		if (StringUtils.isBlank(rateEnd)) {
			obj.put("msg", "利率范围结束不可为空");
			JSONUtils.printObject(obj);
			return;
		} else if (rateEndDouble == 0) {
			obj.put("msg", "利率范围结束格式错误");
			JSONUtils.printObject(obj);
			return;
		} else if (rateEndDouble < 1 || rateEndDouble > 24) {
			obj.put("msg", "年利率范围1%-24%，请在此范围内选择利率");
			JSONUtils.printObject(obj);
			return;
		}
		if (StringUtils.isBlank(remandAmount)) {
			obj.put("msg", "账户保留金额不可为空");
			JSONUtils.printObject(obj);
			return;
		} else if (bool==false) {
			obj.put("msg", "账户保留金额格式错误");
			JSONUtils.printObject(obj);
			return;
		}
		returnId = myHomeService.automaticBidModify(bidAmountDouble,
				rateStartDouble, rateEndDouble, deadlineStartDouble,
				deadlineEndDouble, creditStartDouble, creditEndDouble,
				remandAmountDouble, user.getId()/*, borrowWay*/);

		if (returnId <= 0) {
			obj.put("msg", "操作失败");
		} else {
			obj.put("msg", "操作成功");
		}
		JSONUtils.printObject(obj);

	}

	public void wchatJsSDKConfig() throws Exception {
		JSONObject obj = new JSONObject();
		String url = Convert.strToStr(paramMap.get("url"), "");

		Map<String, String> wxConfigMap = WechatUtils.jSdkConfig(url);
		obj.put("wxConfigMap", wxConfigMap);
		JSONUtils.printObject(obj);
	}
	
	public String wchatFundRecord() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		pageBean.setPageNum(SqlInfusion
				.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(10);
		rechargeService.queryFundrecordList(pageBean, userId, null,
				null, 0, -1);
		if (pageBean.getTotalNum() > 0) {
			request().setAttribute("fundRecordList", pageBean.getPage());
		} else {
			request().setAttribute("fundRecordList", null);

		}
		request().setAttribute("currentPage", pageBean.getPageNum());
		request().setAttribute("totalPageNum", pageBean.getTotalPageNum());
		return SUCCESS;
	}
	
	public String wchatFootPrint() throws Exception {
		String mobilePhone = SqlInfusion.FilteSqlInfusion(request("mobile"));
		Map<String,String> userMap = userService.queryUserBymobilePhone(mobilePhone);
		if(null == userMap){
			return null;
		}
		long userId = Convert.strToLong(userMap.get("id"), -1);
		Map<String, String> rankMap = myHomeService.getMyRank(userId);
		List<Map<String, Object>> timeLine =  myHomeService.getTimeLine(userId);
		request().setAttribute("rankMap", rankMap);
		request().setAttribute("timeLine", timeLine);
		return SUCCESS;
	}
	
	public String wchatRepaymentRemind() throws Exception {
		return SUCCESS;
	}
	
	public String wchatUserCenter() throws Exception {
		User user = this.getUser();
		Long userId = user.getId();
		if (userId == null) {
			return null;
		}
		Map<String, String> pmap = userService.queryPersonById(user.getId());
		Map<String, String> umap = userService.queryUserById(user.getId());
		// 实名认证
		Map<String, String> materialsauthMap = userService.isCheckIDCard(user
				.getId());
		if (materialsauthMap == null || materialsauthMap.size() == 0
				|| !(materialsauthMap.get("auditStatus").equals("3"))) {
			user.setIsBindIdNo(0);
		} else {
			user.setIsBindIdNo(1);
		}
		// 绑定手机
		if (StringUtils.isNotEmpty(pmap.get("cellPhone"))) {
			user.setIsBindMobile(1);
		} else {
			user.setIsBindMobile(0);
		}
		// 支付密码
		String password = umap.get("password");
		String dealpwd = umap.get("dealpwd");
		if (StringUtils.isNotEmpty(password) && StringUtils.isNotEmpty(dealpwd)) {
			if (!password.equals(dealpwd)) {
				user.setCode(1);
			} else {
				user.setCode(0);
			}
		}
		// 密保问题
		// 根据用户ID查询
		Map<String, String> map = userService.queryQuestion(user.getId());
		if (null != map && map.size() > 1) {
			session().setAttribute("isBindQuestion", 1);
		} else {
			session().setAttribute("isBindQuestion", 0);
		}
		// add by sunbing start
		if ("".equals(user.getEmail()) || null == user.getEmail()) {
			session().setAttribute("isBindEmail", 0);
		} else {
			session().setAttribute("isBindEmail", 1);
		}
		// add by sunbing end
		session().setAttribute(IConstants.SESSION_USER, user);
		request().setAttribute("userMap", umap);
		return "success";
	}

}
